const express = require("express");
const router = express.Router();
const con = require("../db/mysql")


router.get('/', async (req, res, next) => {
  const { page, limit,pid } = req.query;
  let where = "1 ";
  if (pid != undefined) {
    where += `AND pid=${pid}`
  }
  try {
    await con.query(`SELECT * FROM category where ${where}   ORDER BY id ASC LIMIT ${limit * 1} OFFSET ${(page - 1) * limit}; SELECT COUNT(*) AS total FROM category where ${where} `, (err, result) => {
      res.json({
        msg: "查询成功",
        code: 200,
        data: result[0],
        total: result[1][0].total
      });
    });
  } catch (error) {
    console.log(error);

  }

});

router.post('/', async (req, res, next) => {
  const { category_name, thumb, pid, sort } = req.body;
  try {
    const result = await con.query(`INSERT INTO category (category_name,thumb,pid,sort) VALUES (?, ?, ?,?)`, [category_name, thumb, pid, sort]);
    if (result.affectedRows === 1) {
      res.json({
        msg: "添加成功",
        code: 200
      });
    } else {
      res.json({
        msg: "添加失败",
        code: 500
      });
    }
  } catch (error) {
    console.log(error);
  }
});


router.delete('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await con.query(`DELETE FROM category WHERE id=?`, id, (err, result) => {
      if (result.affectedRows === 1) {
        res.json({
          msg: "删除成功",
          code: 200
        });
      } else {
        res.json({
          msg: "删除失败",
          code: 500
        });
      }
    });
  } catch (error) {
    console.log(error);

  }

});

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { category_name,thumb,pid,sort} = req.body;
  try {
    const result2 = await con.query(`UPDATE category SET category_name=?,thumb=?,pid=?,sort=? WHERE id=?`, [category_name,thumb,pid,sort,id]);
    if (result2.affectedRows === 1) {
      res.json({
        msg: "更新成功",
        code: 200
      });
    } else {
      res.json({
        msg: "更新失败",
        code: 500
      });
    }

  } catch (e) {
    console.log(e);
  }

});

module.exports = router;











module.exports = router;